package com.logictech.activity.system.web;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.logger.Logger;
import org.jeecgframework.p3.core.logger.LoggerFactory;
import org.jeecgframework.p3.core.util.MD5Util;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.logictech.activity.system.entity.Menu;
import com.logictech.activity.system.entity.SystemUser;
import com.logictech.activity.system.service.SystemAuthService;
import com.logictech.activity.system.service.SystemUserService;
import com.logictech.activity.system.vo.LoginUser;
import com.logictech.common.util.data.StringUtils;
import com.logictech.lims.service.LogService;

@Controller
@RequestMapping({ "/system" })
public class LoginController extends BaseController {
	public static final Logger LOG = LoggerFactory.getLogger(LoginController.class);


	@Autowired
	private SystemAuthService systemAuthService;

	@Autowired
	private SystemUserService systemUserService;
	
	@Resource
	private LogService logService;

	@RequestMapping(value = { "/noAuth" }, method = { RequestMethod.GET, RequestMethod.POST })
	public void noAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String viewName = "base/back/common/error.vm";
		VelocityContext velocityContext = new VelocityContext();
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	@RequestMapping(value = { "/login" }, method = { RequestMethod.GET, RequestMethod.POST })
	public void login(String userId, String password, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String viewName = "base/back/common/login.vm";
		VelocityContext velocityContext = new VelocityContext();
		
		// 用户列表
		List<SystemUser> systemUserList = systemUserService.queryNormalList();
		velocityContext.put("userList", systemUserList);
		
		try {
			LoginUser user = (LoginUser) request.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");

			if (user != null) {
				viewName = "base/back/main/index.vm";
				velocityContext.put("username",  user.getUserName());
				velocityContext.put("userid", user.getUserId());
				try {
					LinkedHashMap<Menu, ArrayList<Menu>> menuTree = this.systemAuthService
							.getSubMenuTree(user.getUserId(), null);
					velocityContext.put("OPERATE_WEB_MENU_TREE", menuTree);
					ViewVelocity.view(request, response, viewName, velocityContext);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
			
			if (!StringUtils.isEmpty(userId) && !StringUtils.isEmpty(password)) {
				user = this.systemUserService.queryUserByUserId(userId);
				if (user != null) {
					String passwordEncode = MD5Util.MD5Encode(password, "utf-8");
					if ((passwordEncode != null) && (passwordEncode.equals(user.getPassword()))) {
	
						if(!"NORMAL".equals(user.getUserStat())){
							velocityContext.put("message", "用户【" + userId + "】无效");
							
						}else{
							request.getSession().setAttribute("OPERATE_WEB_LOGIN_USER", user);
							velocityContext.put("username", user.getUserName());
							velocityContext.put("userid", user.getUserId());
							
							try {
								LinkedHashMap<Menu, ArrayList<Menu>> menuTree = this.systemAuthService
										.getSubMenuTree(user.getUserId(), null);
								velocityContext.put("OPERATE_WEB_MENU_TREE", menuTree);
								viewName = "base/back/main/index.vm";
								ViewVelocity.view(request, response, viewName, velocityContext);
								
								logService.doAdd(user.getUserName() + "登录系统（PC端）");
							} catch (Exception e) {
								e.printStackTrace();
							}
							return;
						}
					}else{
						velocityContext.put("message", "用户【" + userId + "】密码错误");
					}
				} else {
					velocityContext.put("message", "用户【" + userId + "】不存在");
					LOG.info("用户【" + userId + "】不存在");
				}
			}
		} catch (Exception e) {
			LOG.info("登录失败：用户【" + userId + "】" + e.getMessage());
		}
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	@RequestMapping(value = { "/logout" }, method = { RequestMethod.GET, RequestMethod.POST })
	public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
		LoginUser user = (LoginUser) request.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");
		if(user != null){
			logService.doAdd(user.getUserName() + "退出系统（PC端）");
		}
		String viewName = "base/back/common/login.vm";
		VelocityContext velocityContext = new VelocityContext();
		
		// 用户列表
		List<SystemUser> systemUserList = systemUserService.queryNormalList();
		velocityContext.put("userList", systemUserList);
				
		request.getSession().removeAttribute("OPERATE_WEB_LOGIN_USER");
		ViewVelocity.view(request, response, viewName, velocityContext);
	}
	
	@RequestMapping(value = { "/print" }, method = { RequestMethod.GET, RequestMethod.POST })
	public void print(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String viewName = "base/back/common/print.vm";
		VelocityContext velocityContext = new VelocityContext();
		ViewVelocity.view(request, response, viewName, velocityContext);
	}
	
	@RequestMapping(value = { "/back/toEditPassword" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public void toEditPassword(HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "system/back/systemPassword-edit.vm";
		ViewVelocity.view(request, response, viewName, velocityContext);
	}
	
	@RequestMapping(value = { "/back/editPassword" }, method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public AjaxJson editPassword(@RequestParam(required = true, value = "oldPassword") String oldPassword, @RequestParam(required = true, value = "newPassword") String newPassword, @RequestParam(required = true, value = "newPassword2") String newPassword2, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		AjaxJson j = new AjaxJson();
		try {
			LoginUser user = (LoginUser) request.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");
			String userid = user.getUserId();
			// 验证新密码两次输入是否一致
			if(!newPassword.equals(newPassword2)){
				j.setSuccess(false);
				j.setMsg("两次输入密码不一致");
				return j;
			}
			
			// 验证旧密码是否正确
			user = this.systemUserService.queryUserByUserId(userid);
			if (user != null) {
				String passwordEncode = MD5Util.MD5Encode(oldPassword, "utf-8");
				if ((passwordEncode != null) && (passwordEncode.equals(user.getPassword()))) {
					SystemUser systemUser = new SystemUser();
					String newPasswordEncode = MD5Util.MD5Encode(newPassword, "utf-8");
					systemUser.setUserId(userid);
					systemUser.setPassword(newPasswordEncode);
					systemUser.setId(user.getId());
					// 设置密码
					this.systemUserService.doEdit(systemUser);
				}else{
					j.setSuccess(false);
					j.setMsg("旧密码输入有误");
					return j;
				}
			}
			
			j.setMsg("密码修改成功");
			request.getSession().removeAttribute("OPERATE_WEB_LOGIN_USER");
		} catch (Exception e) {
			log.info(e.getMessage());
			j.setSuccess(false);
			j.setMsg("密码修改失败");
		}
		return j;
	}
	
	@RequestMapping(value = { "/back/isAlive" }, method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public AjaxJson checkSession(HttpServletRequest request,HttpServletResponse response) throws Exception {
		return new AjaxJson();
		
	}
	
}
